<template>
  <tbc-dialog title="设置模型" ref="dialog" @confirm="formSubmit">
    <el-form label-position="top">
      <el-form-item label="类型">
        <el-input placeholder="请选择类型" readonly v-model="form.model_name" @click="$refs.model.show()">
          <template #append>
            <el-button icon="el-icon-search" @click="$refs.model.show()">选择</el-button>
          </template>
        </el-input>
      </el-form-item>
      <el-form-item>
        <el-checkbox :label="1" v-model="isSyncChildren">同步所有子分类</el-checkbox>
      </el-form-item>
    </el-form>
  </tbc-dialog>
  <goods-model-selector ref="model" @choice="onModelSelected"/>
</template>
<script lang="ts">
import {
  defineComponent, defineAsyncComponent, reactive,
  toRefs, Ref, ref
} from 'vue'
import http from '@/plugin/http'
import {ElMessage} from "element-plus";

export default defineComponent({

  name: 'goods-cat-set-model',

  components: {
    GoodsModelSelector: defineAsyncComponent(() =>
        import('./GoodsModelSelector.vue'))
  },

  emits: ['success'],

  setup(props, {emit}) {
    const dialog: Ref = ref(null)
    const model: Ref = ref(null)
    const state = reactive({
      form: {model_id: '', model_name: '', cat_id: '', is_sync_children: 0},
      isSyncChildren: false
    })

    const show = (data: Record<string, string>) => {
      init(data)
      state.form.cat_id = data.cat_id
      dialog.value.show()
    }

    const init = (data: Record<string, string>) => {
      state.form.model_id = data.model_id
      state.form.model_name = data.model_name
    }

    const onModelSelected = (data: Record<string, string>) => {
      init(data)
      model.value.close()
    }

    const formSubmit = async () => {
      state.form.is_sync_children = 1
      const res = await http.post('/goods.category/setModel', state.form)
      if (res.data.code !== 0) return ElMessage.error(res.data.message)
      ElMessage.success(res.data.message)
      dialog.value.close()
      emit('success')
    }

    return {
      ...toRefs(state),
      dialog,
      model,
      show,
      onModelSelected,
      formSubmit
    }
  }
})
</script>